package com.github.aloxc.plugin.restplus.entity;

import com.intellij.openapi.util.text.StringUtil;
import org.apache.http.Header;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
 *
 * @author leero
 */
public class HttpResponseHeaders {
    private static final String EMPTY_HEADERS = "Empty";
    private Header[] headers;

    public HttpResponseHeaders(Header[] headers) {
        this.headers = headers;
    }

    public Header[] getHeaders() {
        return headers;
    }

    public void setHeaders(Header[] headers) {
        this.headers = headers;
    }

    @Nullable
    public String valueOf(@NotNull String name) {
        for (Header header : this.headers) {
            if (StringUtil.equalsIgnoreCase(header.getName(), name)) {
                return header.getValue();
            }
        }
        return null;
    }

    @Nullable
    public List<String> valuesOf(@NotNull String name) {
        List<String> values = new ArrayList<>();
        for (Header header : this.headers) {
            if (StringUtil.equalsIgnoreCase(header.getName(), name)) {
                values.add(header.getValue());
            }
        }
        return values;
    }


    @Override
    public String toString() {
        if (this.headers.length == 0) {
            return EMPTY_HEADERS;
        }
        return Stream.of(this.headers).map(header -> header.getName() + ": " + header.getValue()).collect(Collectors.joining("\n"));
    }
}
